<template>
	<view>
		<cu-custom  bgColor="bg-black-two"  :isBack="false">
			<block slot="content">能耗</block>
		</cu-custom>
		<view class="my-bg">
			<view class="flex solid-bottom align-start">
				<view class="flex-sub radius text-center">
					<view class="text-xxl text-white">{{sumMonth}}</view>
					<view class="text-gray">当月总能耗/KWh</view>
				</view>
				<view class="flex-sub radius text-center">
					<view class="text-xxl text-white">{{sumDay}}</view>
					<view class="text-gray">当日总能耗/KWh</view>
				</view>
			</view>			
		</view>
		

		
		<view class="my-bg">
			<view class="text-white margin-bottom-xs">单台机器当月能耗</view>
			<view class="lockParent">
				
				<view class="flex">
					<view class="flex-treble">
						<view @click="openMonth()" class="radius text-center"  style="color: #fff;border: 1px solid #00A99D;padding: 5px;width: 45%;">
							{{selectedYearMonth}}
							<text class="cuIcon-unfold"
								style="color: #00A99D;font-size: 15px; font-weight: bold;"></text>
						</view>
						<view v-if="showMonth" class="bg-white">
							<view class="flex" 
								style="border-bottom: 1px solid #ccc;padding: 10px;margin: 0px 10px;">
								<!-- <view class="flex-sub">上一年</view> -->
								<view class="flex-treble text-center">
									{{fullYear}}年
								</view>
								<!-- <view class="flex-sub">下一年</view> -->
							</view>
							<view class="flex flex-wrap text-center" style="padding: 10px;">
								<view v-for="(item,index) in 12" :key="index" 
									@click="confirmMonth(index+1)"
									:class="selectedMonth == (index+1) ? 'selected-bg' : ''"
									class="basis-xs" style="flex-basis: 25%;padding: 5px;">
									{{Number(index+1)}}月
								</view>
							</view>
						</view>
					</view>
					<view class="flex-sub text-right text-gray">
						单位/KWh
					</view>
				</view>
				<view style="margin-top: 5px;">
					<!-- 区域滚动视图：纵向滚动 -->
					<view>
						<scroll-view :scroll-top="scrollTop" scroll-y="true" class="scroll-Y" @scrolltoupper="upper" @scrolltolower="lower"
						@scroll="scroll">
							<view v-for="(item,index) in machineTableList" :key="index"
								:class="index%2 ? 'flex padding-xs scroll-view-item':'flex padding-xs tr-bg scroll-view-item'">
								<view class="flex-sub text-center">{{item.machine_name}}</view>
								<view class="flex-treble text-center">{{item.run_energy}}</view>
							</view>
						</scroll-view>
					</view>
					<view @tap="goTop" class="text-center" style="color: #00A99D;font-size: 13px;margin-top: 8px;">
						点击这里返回顶部
					</view>
				</view>
				<!-- 判断模块是否解锁 0：加锁，1：解锁 -->
				<view v-if="!moduleLockList.energy1.status" 
					@click="showModal('DialogModal1',moduleLockList.energy1)"
					class="lockView">
					<image src="@/static/image/lock.png" mode='aspectFit'></image>
					<view class="locktext">
						解锁此模块提高生产效率
					</view>
				</view>
			</view>			
		</view>
		<view class="my-bg">
			<view class="flex text-white margin-bottom-xs">
				<view class="flex-sub">月总能耗</view>
				<view class="flex-sub text-right text-gray">单位/KWh</view>
			</view>
			<view class="lockParent" style="height: 150px">
				<l-echart ref="chartBar"></l-echart>
				<!-- 判断模块是否解锁 0：加锁，1：解锁 -->
				<view v-if="!moduleLockList.energy2.status" 
					@click="showModal('DialogModal1',moduleLockList.energy2)"
					class="lockView">
					<image src="@/static/image/lock.png" mode='aspectFit'></image>
					<view class="locktext">
						解锁此模块提高生产效率
					</view>
				</view>
			</view>
		</view>
		<view class="my-bg">
			<view class="flex text-white margin-bottom-xs">
				能耗/产量分析
			</view>
			<view class="lockParent" style="height: 180px">
				<l-echart ref="chartLine"></l-echart>
				<!-- 判断模块是否解锁 0：加锁，1：解锁 -->
				<view v-if="!moduleLockList.energy3.status" 
					@click="showModal('DialogModal1',moduleLockList.energy3)"
					class="lockView">
					<image src="@/static/image/lock.png" mode='aspectFit'></image>
					<view class="locktext">
						解锁此模块提高生产效率
					</view>
				</view>
			</view>
		</view>
		
		
		<!-- 购买模块 模态框 -->
		<view class="cu-modal" :class="modalName=='DialogModal1'?'show':''">
			<view class="cu-dialog bg-white" style="border-radius: 13px;">
				<view class="cu-bar justify-end">
					<view class="content text-black-two">解锁模块</view>
				</view>
				<view class="margin-bottom-sm">
					<view>
						<image mode='widthFix' src="@/static/image/unLock.png" class="tip-img"></image>
					</view>
					<view>
						<text style="color: #00A99D;font-size: 30px;">{{modulePrice}}</text>
						<text class="text-gray padding-left-xs" style="font-size: 14px;">元</text>
					</view>
					<view class="text-gray" style="font-size: 15px;">
						您确认开通此模块？
					</view>
				</view>
				<view class="cu-bar padding-bottom-sm" style="height: 80px;">
					<view class="action margin-0 flex-sub text-green" @tap="hideModal">
						<button class="cu-btn round lines-green-two padding-lr-lg" style="width: 90%;height: 45px;">
							<text class="text-gray">取消</text>
						</button>
					</view>
					<view class="action margin-0 flex-sub">
						<button  @click="showModalInvoice('fapiaoTip')" class="cu-btn round bg-green-two padding-lr-lg" style="width: 90%;height: 45px;">确认去开票</button>
					</view>
				</view>
			</view>
		</view>		
		<!-- 发票过渡提醒框 -->
		<view class="cu-modal" :class="modalName=='fapiaoTip'?'show':''">
			<view class="cu-dialog bg-white" style="border-radius: 13px;">
				<view class="cu-bar justify-end">
					<view class="content text-black-two">发票提醒</view>
				</view>
				<view class="margin-bottom-sm">
					<view>
						<image src="@/static/image/fapiao-tip.png"  mode='widthFix' class="tip-img"></image>
					</view>
					<view class="text-black-two padding-top-sm" style="font-size: 15px;">
						感谢您信任并使用我司开发的产品！
						<br/>
						我司的电子发票统一采取国家税务局
						<br/>
						认证的电子普票。
					</view>
				</view>
				<view class="cu-bar padding-bottom-sm" style="justify-content: center;height: 80px;">
					<view><image src="@/static/image/fapiao-gif.gif" style="width: 64px;height: 64px;"></image></view>
				</view>
			</view>
		</view>
		<view class="cu-modal" :class="modalName=='Modal'?'show':''">
			<view class="cu-dialog bg-white" style="height: 100px;width: 80%;">
				<view class="cu-bar justify-end">
					<view class="content text-black-two" style="font-size: 14px;">提示</view>
				</view>
				<!-- 提示3：橙色 #ff5722  错误2：红色 red   正确1：绿色 #00A99D  -->
				<view v-if="tipFlag == 3" class="text-black-two" style="font-size: 16px;color: #ff5722;">
					{{resText}}
				</view>
				<view v-else-if="tipFlag == 2" class="text-black-two" style="font-size: 16px;color: red;">
					{{resText}}
				</view>
				<view v-else="tipFlag == 1" class="text-black-two" style="font-size: 16px;color: #00A99D;">
					{{resText}}
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import * as echarts from '@/uni_modules/lime-echart/static/echarts.min'
	var _self;
	export default {
		data() {
			return {
				selectedMonth:0,//选中的月份，默认是当前月
				showMonth:0,//1是打开月历，0是隐藏
				nowDate:"",
				fullYear:"",//当前年
				month:"",
				endOfMonth:"",
				endDate:"",
				startDate:"",
				selectedYearMonth:"",
				
				// 纵向滚动
				scrollTop: 0,
				old: {
					scrollTop: 0
				},
				moduleLockList:[],//模块列表
				modalName:null,//弹出是否解锁模块的模态框
				modulePrice:0,//模块价格
				buyModuleInfo:[],//购买当前模块的模块信息
				resText:'',
				tipFlag:0,//提示flag(1:正确，2：错误，3：提示)
				
				//当月总能耗
				sumMonth:0,
				//当日总能耗
				sumDay:0,
				//单台机器当月能耗list
				machineTableList:[],
				//月总能耗list-柱状图
				barMonthList:[],
				//能耗产量分析list-折线图
				lineMonthList:[],
				//月总能耗-柱状图
				optionBar: {
					tooltip: {
						trigger: 'axis',
						axisPointer: {            // 坐标轴指示器，坐标轴触发有效
							type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
						}
					},
					grid: {
						left: '1%',
						right: '1%',
						bottom: '1%',
						top:'12%',
						containLabel: true
					},
					xAxis: {
						type: 'category',
						data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月'],
						axisLabel: {
							color: "#aaaaaa"
						},
						
					},
					yAxis: {
						type: 'value',
						axisLabel: {
							color: "#aaaaaa"
						},
						axisLine: {
							show: true,
							lineStyle: {
								color: "#62626A"
							}
						},
						axisTick:{
							lineStyle:{
								color:"red"
							}
						},
						splitLine:{
							show: false,
							lineStyle:{
								color: "#62626A"
							}
						}
					},
					//数据区域缩放组件
					 dataZoom: {
					    start: 30,
					    type: "inside",
						zoomLock:true,//只平移不缩放
					  },
					series: [{
						data: [120, 200, 150, 80, 70, 110, 130],
						type: 'bar',
						color: "#FBB03B",
						barWidth: 12
					}]
				},
				optionLine:  {
					tooltip: {
						trigger: 'axis'
					},
					legend: {
						data: ['日能耗/kwh', '日产量/件'],
						bottom: 0,
						textStyle: {
							color: "#aaaaaa",
							lineHeight: 1
						},
					},
					grid: {
						top:'12%',
						left: '1%',
						right: '1%',
						bottom: '17%',
						containLabel: true
					},
					xAxis: {
						type: 'category',
						// boundaryGap: false,
						data: ['8:00', '9:00', '10:00', '11:00', '12:00', '13:00', '14:00'],
						axisLabel: {
							color: "#aaaaaa"
						},
					},
					yAxis: {
						type: 'value',
						axisLabel: {
							color: "#aaaaaa"
						},
						axisLine: {
							show: true,
							lineStyle: {
								color: "#62626A"
							}
						},
						splitLine:{
							show: true,
							lineStyle:{
								color: "#62626A"
							}
						}
					},
					//数据区域缩放组件
					 dataZoom: {
					    start: 10,
					    type: "inside",
						zoomLock:true,//只平移不缩放
					  },
					series: [
						{
							name: '日能耗/kwh',
							type: 'line',
							stack: '总量',
							data: [120, 132, 101, 134, 90, 230, 210],
							symbol: "rect",
							itemStyle: {
								color: "#FBB03B"
							}
						},
						{
							name: '日产量/件',
							type: 'line',
							stack: '总量',
							data: [220, 182, 191, 234, 290, 330, 310],
							symbol: "rect",
							itemStyle: {
								color: "#17B38B"
							}
						}
					]
				},
			}
		},
		async mounted() {
			/* //月总能耗
			this.$refs.chartBar.init(echarts, chartBar=> {
				chartBar.setOption(this.optionBar);
			});
			//能耗/产量分析
			this.$refs.chartLine.init(echarts, chartLine=> {
				chartLine.setOption(this.optionLine);
			}); */
		},
		onShow(){
			_self = this;
			//获取模块购买列表
			this.getModelLockData();
			//获取当前月
			this.currentYearMonth();
			//初始化获取数据
			this.getInitData();
			//选择月份查询单台机器月能耗
			this.getMachineEnergy();
		},
		methods: {
			//获取模块列表，判断是否购买，未购买则加锁
			async getModelLockData(){
				// position =>  1:首页，2:设备，3:能耗，4:报表
				let [err,res] = await this.$http.post('getModelList',{position:3},{
					token:true,
					checkToken:true ,
				});
				//status：0（加锁），1：解锁
				this.moduleLockList = res.data.data;
			},
			//打开模态框
			showModal(name,data=null){
				this.modalName=name
				this.buyModuleInfo = data;//购买该模块的信息
				this.modulePrice = data.module_price;//购买该模块的价格
			},
			//隐藏模态框
			hideModal(e) {
				this.modalName = null
			},
			//打开模态框
			showModalTip(val,isflag){
				this.modalName='Modal';
				this.resText = val;
				this.tipFlag = isflag;
			},
			//隐藏模态框
			hideModalTip(e) {
				this.modalName = null
				this.resText = '';
			},
			//发票过渡
			showModalInvoice(name){
				//获取当前登录用户实时余额
				let currentYue = uni.getStorageSync("userinfo").money;
				//获取用户余额，判断余额是否足够
				if (parseInt(currentYue) >= parseInt(this.modulePrice)) {
					//余额足够跳转到发票页
					this.modalName=name;
					setTimeout(function () {
						_self.modalName = null
						_self.buyModule();
					},3000);
				} else {
					//余额不足提示请充值，跳转到余额充值页
					this.showModalTip('余额不足请充值',3);
					setTimeout(function () {
						_self.hideModalTip();
						uni.navigateTo({
							url:'/pages/center/yue/yue',
						})
					}, 2000);
				}
			},
			//确认购买模块跳转到发票页
			buyModule(){
				//购买该模块的信息
				let data = JSON.stringify(this.buyModuleInfo);
				uni.navigateTo({
					url:'/pages/center/fapiao/buy-module-fapiao?moduleInfo='+data,
				})	
			},
			//表格滚动
			upper: function(e) {
				console.log(e)
			},
			lower: function(e) {
				console.log(e)
			},
			scroll: function(e) {
				console.log(e)
				this.old.scrollTop = e.detail.scrollTop
			},
			goTop: function(e) {
				// 解决view层不同步的问题
				this.scrollTop = this.old.scrollTop
				this.$nextTick(function() {
					this.scrollTop = 0
				});
				// uni.showToast({
				// 	icon:"none",
				// 	title:"纵向滚动 scrollTop 值已被修改为 0"
				// })
			},
			//选中月份
			confirmMonth(val){
				//选中的月
				this.selectedMonth = val;
				//关闭月历
				this.showMonth = 0;
				this.fullYear = this.nowDate.getFullYear();
				//获取选中月的第一天 
				this.startDate = this.filterTime(new Date(this.fullYear,val,1).getTime());//年，月，日
				//获取选中月的最后一天
				this.endDate = this.filterTime(new Date(this.fullYear,val,0).getTime());//年，月，日
				this.selectedYearMonth = this.fullYear+'年'+val+'月';
				this.getMachineEnergy();
			},
			//打开月历
			openMonth(){
				this.showMonth = 1;
			},
			async getInitData(){
				let startDate = this.fullYear+'-'+this.selectedMonth+'-01';
				uni.showLoading({ title: '加载中...', mask: true });
				let [err,res] = await this.$http.post('getEnergyData',{startDate : startDate},{
					token:true,
					checkToken:true ,
				});
				// 失败
				if (!this.$http.errorCheck(err,res)){
				uni.hideLoading();
				return false;
				}
				uni.hideLoading();
				//当月总能耗
				this.sumMonth = res.data.data.month_energy;
				//当日总能耗
				this.sumDay = res.data.data.today_energy;
				//柱状图：x轴
				this.optionBar.xAxis.data = res.data.data.bar_month_list.xAxis;		
				//柱状图：y轴
				this.optionBar.series[0].data = res.data.data.bar_month_list.yAxis;
				//月总能耗
				this.$refs.chartBar.init(echarts, chartBar=> {
					chartBar.setOption(this.optionBar);
				});
				//折线图:x轴
				this.optionLine.xAxis.data = res.data.data.line_list.xAxis;
				//折线图:y轴1:日能耗
				this.optionLine.series[0].data = res.data.data.line_list.energy_yAxis;
				//折线图:y轴2：日产量
				this.optionLine.series[1].data = res.data.data.line_list.output_yAxis;				
				//能耗/产量分析
				this.$refs.chartLine.init(echarts, chartLine=> {
					chartLine.setOption(this.optionLine);
				});
			},
			//获取单台机器的月能耗
			async getMachineEnergy(){
				let startDate = this.fullYear+'-'+this.selectedMonth+'-01';
				uni.showLoading({ title: '加载中...', mask: true });
				let [err,res] = await this.$http.post('getMachineEnergy',{startDate : startDate},{
					token:true,
					checkToken:true ,
				});
				// 失败
				if (!this.$http.errorCheck(err,res)){
				uni.hideLoading();
				return false;
				}
				uni.hideLoading();
				this.machineTableList = res.data.data;
				console.log(res);
			},
			
			
			// 时间戳转为正常时间的公共方法，当然你也可以加上小时、分、秒
			filterTime(time) {
			  const date = new Date(time)
			  const Y = date.getFullYear()
			  const M = date.getMonth() + 1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1 
			  const D = date.getDate()
			  return `${Y}-${M}-${D}`
			},
			
			getFullDate(targetDate) {
				var D, y, m, d;
				if (targetDate) {
					D = new Date(targetDate);
					y = D.getFullYear();
					m = D.getMonth() + 1;
					d = D.getDate();
				} else {
					y = fullYear;
					m = month;
					d = date;
				}
				m = m > 9 ? m : '0' + m;
				d = d > 9 ? d : '0' + d;
				return y + '-' + m + '-' + d;
			},
			//上一月
			last(){
				this.nowDate.setMonth(this.nowDate.getMonth()-1);
				this.startDate = this.nowDate.getFullYear() + "-" + (this.nowDate.getMonth()+1) + "-" + this.nowDate.getDate()
				this.endDate =this.getFullDate(new Date(this.nowDate.getFullYear(), this.nowDate.getMonth() + 1, 0)) 	
				this.selectedYearMonth = this.nowDate.getFullYear()+'-'+(this.nowDate.getMonth()+1);
			},
			//下一月
			next(){
				this.nowDate.setMonth(this.nowDate.getMonth()+1);
				this.startDate = this.nowDate.getFullYear() + "-" + (this.nowDate.getMonth()+1) + "-" + this.nowDate.getDate()
				this.endDate =this.getFullDate(new Date(this.nowDate.getFullYear(), this.nowDate.getMonth() + 1, 0))
			},
			//当前月
			currentYearMonth(){
				this.nowDate = new Date();
				this.fullYear =  this.nowDate.getFullYear();
				this.month = this.nowDate.getMonth() + 1; // getMonth 方法返回 0-11，代表1-12月
				this.endOfMonth = new Date(this.fullYear, this.month, 0).getDate(); // 获取本月最后一天
				this.endDate = this.getFullDate(this.nowDate.setDate(this.endOfMonth));//当月最后一天
				this.startDate = this.getFullDate(this.nowDate.setDate(1));//当月第一天
				this.selectedYearMonth = this.fullYear+'年'+this.month+'月';
				this.selectedMonth = this.nowDate.getMonth() + 1;
			},
			//打开日历
			open() {
				this.$refs.calendar.open()
			},
			close() {
				console.log('弹窗关闭');
			},
			confirm(e) {
				this.startDate = e.fulldate;
				console.log('confirm 返回:', e)
			},
		}
	}
</script>


<style>
.children{
	width: 100%;
    /* 下面的 120 rpx 是该子组件上方其它子组件占用的高度 */
	height: calc(100vh - 120rpx);
}
	.selected-bg{
		background-color: #00A99D;
		font-weight: bold;
	}
	.scroll-Y {
		height: 300rpx;
	}
	.scroll-view-item {
		height: 30px;
	}
	.tr-bg{
		background-color: #171723;
	}
</style>